package servlet;

import pojo.User;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //接收rememberMe
        String rememberMe = request.getParameter("rememberMe");
        User user = userService.login(username,password);
        if(user != null){
            //登录成功，跳转到查询所有的BrandServlet
            if("1".equals(rememberMe)){
                //勾选了rememberMe，则发送Cookie
                //1. 创建Cookie对象
                Cookie cookieUsername = new Cookie("username",username);
                Cookie cookiePassword = new Cookie("password",password);
                // 设置Cookie的存活时间7天
                cookieUsername.setMaxAge( 7*24*3600);
                cookiePassword.setMaxAge( 7*24*3600);
                //2. 发送
                response.addCookie(cookieUsername);
                response.addCookie(cookiePassword);
            }else {
                //清除cookie中已有的用户名和密码信息
                Cookie cookieUsername = new Cookie("username",null);
                Cookie cookiePassword = new Cookie("password",null);
                // 设置Cookie的存活时间7天
                cookieUsername.setMaxAge( 0);
                cookiePassword.setMaxAge( 0);
                //2. 发送
                response.addCookie(cookieUsername);
                response.addCookie(cookiePassword);
            }
            //登录成功，跳转到查询所有的BrandServlet
            //将登陆成功后的user对象，存储到session
            HttpSession session = request.getSession();
            session.setAttribute("LOGIN_USER",user);
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/SelectAll");
        }else {
            // 登录失败,
            // 存储错误信息到request
            request.setAttribute("LOGIN_MSG","用户名或密码错误");
            // 转发到login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }
}